package com.zyg.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * RabbitMQ配置类
 */
@Configuration
public class RabbitMQConfig {

    public final static String TOPIC_ZYG_DATA_MSG = "topic.zyg.data.msg";//推送消息交换机，路由键Routing Key
    public final static String EXCHANGE_ZYG_DATA_MSG = "exchange.zyg.data.msg";//推送消息交换机，路由键Routing Key

    /**
     * 队列
     * @return
     */
    @Bean
    public Queue zygDataTopic() {
        return new Queue(TOPIC_ZYG_DATA_MSG);
    }

    /**
     * 交换机
     * @return
     */
    @Bean
    TopicExchange zygExchange() {
        //设置交换机为topic模式,即按规则转发消息，并设置routing_key
        return new TopicExchange(EXCHANGE_ZYG_DATA_MSG);
    }

    /**
     * 声明绑定关系
     * @return
     */
    @Bean
    Binding bindingExchange() {
        //绑定推送消息交换机路由键 //with为路由键匹配规则
        return BindingBuilder.bind(zygDataTopic()).to(zygExchange()).with(TOPIC_ZYG_DATA_MSG);
    }

    @Bean
    @Primary
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public RabbitListenerContainerFactory<?> rabbitListenerContainerFactory(ConnectionFactory connectionFactory){
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(messageConverter());
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return factory;
    }
}
